#include "FeatureExtractorBase.h"
/********************************************************************/
CFeatureExtractorBase::CFeatureExtractorBase(void)
{
}
/********************************************************************/
CFeatureExtractorBase::~CFeatureExtractorBase(void)
{
}
/********************************************************************/
TDataSet CFeatureExtractorBase::GetNormalizationValues( TDataSet &  data)
{
	TDataSet retVal;
	TFeatureVector means, stdDev;
	CalculateAverages(data, means, stdDev); 
	retVal.push_back(means);
	retVal.push_back(stdDev);
	return retVal;
}
/********************************************************************/
TDataSet CFeatureExtractorBase::Normalize( TDataSet& data )
{
	TDataSet retVal; 
	// we're just applying the whitening transform
	// f' = f-mu/sigma
	TFeatureVector means;
	TFeatureVector stdDev;
	CalculateAverages( data, means, stdDev );
	int nfeatures = static_cast<int>(data[0].size());
	int nDataPts = static_cast<int>(data.size());
	// for each image
	double temp =0.00;
	for( int i=0; i<nDataPts; i++ )
	{
		for(int j=0; j<nfeatures; j++ )
		{
			temp = data[i][j];
			if(stdDev[j] != 0 )
			{
				data[i][j] = (temp-means[j])/stdDev[j];
			}
			else
			{
				data[i][j]= 0.00; 
			}
		}
	}

	return retVal;
}
/********************************************************************/
TFeatureVector  CFeatureExtractorBase::GetAllFeatures( TDataSet data, int feature )
{
	TFeatureVector retVal;
	TDataSetIter images;
	for( images = data.begin(); images != data.end(); ++images )
	{
		retVal.push_back(images->at(feature));
	}
	return retVal;
}
/********************************************************************/
void CFeatureExtractorBase::CalculateAverages( TDataSet data, TFeatureVector& means, TFeatureVector& stdDev )
{
	int nfeatures = static_cast<int>(data[0].size());
	double nDataPts = static_cast<double>(data.size());
	for( int i=0; i<nfeatures; ++i )
	{
		TFeatureVector temp = GetAllFeatures( data, i );
		TFeatureVectorIter iter; 
		double accumulator = 0.00;
		for( iter = temp.begin(); iter != temp.end(); ++iter )
		{
			accumulator += *iter;
		}
		double mu = accumulator/nDataPts;
		accumulator = 0.00;
		for( iter = temp.begin(); iter != temp.end(); ++iter )
		{
			accumulator += (*iter-mu)*(*iter-mu);
		}
		double var = accumulator/nDataPts;
		means.push_back(mu);
		stdDev.push_back(sqrt(var)); 
	}
}
/********************************************************************/